import React, { useEffect, useRef, useState } from 'react'
import { Avatar, Card, Col, Drawer, List, Row } from 'antd';
import { EditOutlined, EllipsisOutlined, PieChartOutlined } from '@ant-design/icons';
import axios from 'axios';
import * as ECharts from 'echarts';
import _ from 'lodash';//对数组进行分组输出

const { Meta } = Card;

const Home = (props) => {
  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))

  const barRef = useRef();
  const pieRef = useRef();

  const [ViewList, setViewList] = useState([])
  const [StarList, setStarList] = useState([])
  const [AllList, setAllList] = useState([])
  const [Visible, setVisible] = useState(false)
  const [pieChart, setpieChart] = useState(null)
  useEffect(() => {
    axios.get(`/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`).then((res) => {
      setViewList(res.data)
    })
  }, [])

  useEffect(() => {
    axios.get(`/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`).then((res) => {
      setStarList(res.data)
    })
  }, [])


  useEffect(() => {
    axios.get(`/news?publishState=2&_expand=category`).then((res) => {
      renderBarView(_.groupBy(res.data, item => item.category.title))
      setAllList(res.data)
    })

    return () => {
      window.onresize = null;
    }
  }, [])

  const renderBarView = (obj) => {

    var myChart = ECharts.init(barRef.current);

    var option = {
      title: {
        text: "新闻分类图示"
      },
      tooltip: {},
      legend: {
        data: ["数量"]
      },
      xAxis: {
        data: Object.keys(obj),
        axisLabel: {
          interval: 0,
          rotate: "60 "
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [{
        name: "数量",
        type: "bar",
        data: Object.values(obj).map(item => item.length)
      }]
    };
    myChart.setOption(option);

    // 两种方法
    window.onresize = () => {
      myChart.resize();
    }
    // window.addEventListener("resize", function () {
    //   //通过图表调用resize这个方法
    //   myChart.resize();
    // })
  }

  const showDrawer = () => {
    setVisible(true);
    setTimeout(() => {
      renderPieView()
    }, 0);

  };

  const onClose = () => {
    setVisible(false);
  };

  const renderPieView = (obj) => {
    let currentList = AllList.filter(item => item.author === username)
    let groupObj = _.groupBy(currentList, item => item.category.title)
    let list = [];
    for (const i in groupObj) {
      list.push({
        value:groupObj[i].length,
        name:i
      })
    }
    let myChart;
    if (!pieChart) {
      myChart = ECharts.init(pieRef.current);
      setpieChart(myChart)
    } else {
      myChart = pieChart
    }
    let option = {
      backgroundColor: 'white',
      title: {
        text: `${username}的新闻分类数量图示`,
        left: 'center',
        top: 20
      },
      tooltip: {
        show: true,
        trigger: 'item',
        //{a}(系列名)，{b}(数据项名),{c}(数值),{d}(百分比)
        formatter: "{a} <br/>{b} : {c} ({d}%)",
        backgroundColor: "rgba(1, 13, 19, 0.5)",
        borderWidth: 1,
        textStyle: {
          color: "rgba(212, 232, 254, 1)",
          // fontSize: fontChart(0.24),
        },
        // extraCssText: "z-index:2"
      },

      legend: {
        orient: 'vertical',
        top: 100,
        left: 40,
        itemWidth: 15,
        itemHeight: 10,
        itemGap: 25,
        borderRadius: 4,
        textStyle: {
          color: "#000",
          fontFamily: "Alibaba PuHuiTi",
          fontSize: 14,
          fontWeight: 400,
        },
      },
      series: [
        {
          top:100,
          left:100,
          name: `发布数量`,
          type: 'pie',
          radius: '50%',
          center: ['50%', '40%'],
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    option && myChart.setOption(option)
  }


  return (
    <div>
      <Row gutter={16}>
        <Col span={8}>
          <Card title="用户最常浏览" bordered={false}>
            <List
              size='small'
              // bordered
              dataSource={ViewList}
              renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card title="用户最常浏览" bordered={false}>
            <List
              size='small'
              // bordered
              dataSource={StarList}
              renderItem={(item) => <List.Item><a href={`#/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <PieChartOutlined
                key="piechart"
                onClick={() => {
                  showDrawer()
                }}
              />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://xsgames.co/randomusers/avatar.php?g=pixel" />}
              title={username}
              description={
                <div>
                  <b>{region ? region : "全球"}</b>
                  <span style={{ margin: "0px 20px" }}>{roleName}</span>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>

      <div ref={barRef} style={{
        height: "400px",
        width: "100%",
        marginTop: "30px"
      }}>

      </div>

      <Drawer
        width="600px"
        height="100%"
        title="个人新闻分类"
        placement="right"
        onClose={onClose}
        open={Visible}
      >
        <div ref={pieRef} style={{
          height: "400px",
          width: "100%",
          marginTop: "30px"
        }}>
        </div>
      </Drawer>
    </div>
  )
}

export default Home
